//
//  GHMainViewController.swift
//  GHWeibo
//
//  Created by LGH on 2017/8/3.
//  Copyright © 2017年 LGH. All rights reserved.
//

import UIKit

class GHMainViewController: UITabBarController {

    lazy var composeButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.setupChildControllers()
        self.setupComposeButton()
        
        delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: NSNotification.Name(rawValue: GHUserShouldLoginNotification), object: nil)

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        
        return .portrait
    }
    
    /// 监听撰写微博按钮
    //FIXME: 没有实现
    func composeButtonClick() {
        
        print("撰写微博")
    }
    
    func login(n: Notification) {
        
        let nav = UINavigationController(rootViewController: GHOAuthViewController())
        present(nav, animated: true, completion: nil)
    }

}

// MARK: - 设置界面
extension GHMainViewController {
    
      func setupChildControllers() -> Void {
        
        guard let path = Bundle.main.path(forResource: "main", ofType: "json") ,
              let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
              let arr = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
            else {
            
            return
        }
        
//        let json = try? JSONSerialization.data(withJSONObject: arr, options: [.prettyPrinted])
//        try? json?.write(to: URL(fileURLWithPath: "/Users/LGH/Desktop/main.json"))
        
        var vcArray = [UIViewController]()
        
        for dict in arr {
            
            let vc = controllerFromDictionary(dict: dict)
            vcArray.append(vc)
        }
        
        viewControllers = vcArray
    }

    /// 通过字典创建控制器
    ///
    /// - Parameter dict: 字典信息
    /// - Returns: 返回一个控制器
    private func controllerFromDictionary(dict: [String: Any]) -> UIViewController {
        
        guard  let clsName = dict["clsName"] as? String,
               let title = dict["title"] as? String,
               let imageName = dict["imageName"] as? String,
        let visitorInfo = dict["visitorInfo"] as? [String: String],
               let bundleName = Bundle.main.infoDictionary?["CFBundleName"] as? String,
               let vcClass = NSClassFromString(bundleName + "." + clsName) as? GHBaseViewController.Type
        else {
            
            return UIViewController()
        }
        
        let vc = vcClass.init()
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.visitorInfo = visitorInfo
        let nav = GHNavigationController(rootViewController: vc)
        
        return nav
    }
    
    /// 设置撰写按钮
    func setupComposeButton() {
    
        self.tabBar.addSubview(composeButton)

        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
        
        composeButton.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        composeButton.setBackgroundImage(UIImage(
            named:"tabbar_compose_button_highlighted"),
            for: .highlighted)
        composeButton.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        composeButton.setImage(
            UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .normal)
        composeButton.sizeToFit()
        let x: CGFloat = self.tabBar.bounds.width / 2.0
        let y: CGFloat = self.tabBar.bounds.height / 2.0
        composeButton.center = CGPoint(x: x, y: y)

    }

}

// MARK: -
extension GHMainViewController: UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let index = viewControllers?.index(of: viewController)
        if selectedIndex == 0 && index == selectedIndex {
            
            let nav = viewControllers?[0]
            let vc = nav?.childViewControllers[0] as? GHHomeViewController
            vc?.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: false)
            vc?.loadData()
           
        }
        
        //避免点击撰写按钮时发生界面跳转
        return !viewController.isMember(of: UIViewController.self)
    }
    
}
